package com.imooc.uaa.rest;

import com.imooc.uaa.domain.Auth;
import com.imooc.uaa.domain.User;
import com.imooc.uaa.domain.dto.LoginDto;
import com.imooc.uaa.domain.dto.UserDto;
import com.imooc.uaa.exception.DuplicateProblem;
import com.imooc.uaa.service.UserService;
import com.imooc.uaa.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.nio.file.AccessDeniedException;

@RequiredArgsConstructor
@RestController
@RequestMapping("/authorize")
public class AuthorizeResource {

    private final UserService userService;
    private final JwtUtil jwtUtil;

    @PostMapping("/register")
    public void register(@RequestBody @Valid UserDto userDto) {
        // 1. 检查 username, email, mobile 都是唯一的，所以有查询数据库确保唯一
        if (userService.isUsernameExist(userDto.getUsername())) {
            throw new DuplicateProblem("用户名重复");
        }
        if (userService.isEmailExist(userDto.getEmail())) {
            throw new DuplicateProblem("电子邮件重复");
        }
        if (userService.isMobileExist(userDto.getMobile())) {
            throw new DuplicateProblem("手机号重复");
        }
        // 2. 我们需要  userDto 转换成 User,
        val user = User.builder()
                .username(userDto.getUsername())
                .email(userDto.getEmail())
                .mobile(userDto.getMobile())
                .password(userDto.getPassword())
                .build();
        // 3. 我们给一个默认角色（ROLE_USER）, 然后保存。
        userService.register(user);
    }

    @PostMapping("/token")
    public Auth login(@Valid @RequestBody LoginDto loginDto) throws Exception {
        return userService.login(loginDto.getUsername(), loginDto.getPassword());
    }

    @PostMapping("/token/refresh")
    public Auth refreshToken(
            @RequestHeader(name = "Authorization") String authorization,
            @RequestParam String refreshToken) throws AccessDeniedException {
        val PREFIX = "Bearer";
        val accessToken = authorization.replace(PREFIX, "");
        if (jwtUtil.validateRefreshToken(refreshToken) && jwtUtil.validateAccessTokenWithoutExpiration(accessToken)) {
            return new Auth(jwtUtil.createAccessTokenWithRefreshToken(refreshToken), refreshToken);
        }
        throw new AccessDeniedException("访问被拒接");
    }
}
